package httpclient

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
)

const (
	GET    = "GET"
	POST   = "POST"
	PUT    = "PUT"
	PATCH  = "PATCH"
	DELETE = "DELETE"
)

type ResponseWrapper struct {
	StatusCode int
	Body       string
	Header     http.Header
}

func Get(url string, timeout int) ResponseWrapper {
	req, err := http.NewRequest(GET, url, nil)
	if err != nil {
		return createRequestError(err)
	}
	return Request(req, timeout)
}

func PostJson(url string, body string, timeout int) ResponseWrapper {
	buf := bytes.NewBufferString(body)
	req, err := http.NewRequest(POST, url, buf)
	if err != nil {
		return createRequestError(err)
	}
	req.Header.Set("Content-type", "application/json")
	return Request(req, timeout)
}

func RequestData(method string, url string, body string, header map[string]string, timeout int) ResponseWrapper {
	buf := bytes.NewBufferString(body)
	req, err := http.NewRequest(method, url, buf)
	if err != nil {
		return createRequestError(err)
	}
	for k, v := range header {
		req.Header.Set(k, v)
	}
	return Request(req, timeout)
}

// 请求http数据，超时单位为秒
func Request(req *http.Request, timeout int) ResponseWrapper {
	wrapper := ResponseWrapper{StatusCode: 0, Body: "", Header: make(http.Header)}
	client := &http.Client{}
	if timeout > 0 {
		client.Timeout = time.Duration(timeout) * time.Second
	}
	//setRequestHeader(req)
	resp, err := client.Do(req)
	if err != nil {
		wrapper.Body = fmt.Sprintf("执行HTTP请求错误-%s", err.Error())
		return wrapper
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		wrapper.Body = fmt.Sprintf("读取HTTP请求返回值失败-%s", err.Error())
		return wrapper
	}
	wrapper.StatusCode = resp.StatusCode
	wrapper.Body = string(body)
	wrapper.Header = resp.Header

	return wrapper
}

func createRequestError(err error) ResponseWrapper {
	errorMessage := fmt.Sprintf("创建HTTP请求错误-%s", err.Error())
	return ResponseWrapper{0, errorMessage, make(http.Header)}
}

// func RouteTestTool(method, url string, body io.Reader, utoken string, appSecret string) (string, error) {
// 	req, _ := http.NewRequest(method, url, body)
// 	req.Header.Add("accept", "application/json")
// 	req.Header.Add("content-type", "application/json")
// 	if utoken != "" {
// 		req.Header.Add("utoken", utoken)
// 	}
// 	if appSecret != "" {
// 		req.Header.Add("appSecret", appSecret)
// 	}
// 	if http.StatusOK != w.Code {
// 		fmt.Printf("%v--%v", w.Code, url)
// 		return "", errors.New("httpStatusFail")
// 	}
// 	// 可以先判断状态，再取值 assert.Equal(t, http.StatusOK, w.Code)
// 	body2 := w.Body.String()
// 	return body2, nil
// }
